package com.seasugar.raggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seasugar.raggie.common.R;
import com.seasugar.raggie.model.entity.Category;
import com.seasugar.raggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @GetMapping("page")
    public R getAllCategory(Integer page,Integer pageSize){
        log.info("页数:{},条数:{}",page,pageSize);
        Page pageInfo=new Page(page,pageSize);
        LambdaQueryWrapper<Category> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Category::getSort);
        categoryService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 添加分类分类
     */
    @PostMapping
    public R addCategory(@RequestBody Category category){
        log.info("添加分类名称:{}",category.getName());
        boolean b = categoryService.save(category);
        if(b)
            return R.success("添加成功");
        else
            return R.error("添加失败");
    }

    /**
     * 修改分类分类
     */
    @PutMapping
    public R updateCategory(@RequestBody Category category){
        log.info("修改分类id:{}",category.getId());
        boolean b = categoryService.updateById(category);
        if(b)
            return R.success("修改成功");
        else
            return R.error("修改失败");
    }

    /**
     * 删除分类
     * 1.需要判断分类是否关联了菜品
     */
    @DeleteMapping
    public R deleteCategory(String ids){
        log.info("删除分类id:{}",ids);
        boolean b = categoryService.removeById(ids);
        if(b)
            return R.success("删除成功");
        else
            return R.error("删除失败");
    }

    @GetMapping("list")
    public R type(Integer type){
//        List<Category> categories = categoryService.findCategoriesByType(type);
        LambdaQueryWrapper<Category> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(type!=null,Category::getType,type);
        queryWrapper.orderByAsc(Category::getSort, Category::getUpdateTime);
        List<Category> categories = categoryService.list(queryWrapper);
        if(categories!=null)
            return R.success(categories);
        else
            return R.error("查询失败");
    }
}
